<script setup>
import {computed, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {doDelete, doGet} from "../../util/request.js";
import {confirmMessage, showMessage} from "../../util/message.js";
import {useStore} from "vuex";

// 获取用户信息 vuex 获取用户
const store = useStore();
const loginUser = computed(() => store.state.loginUser);
onMounted(() => {
  store.dispatch('fetchUserInfo');
});

//市场活动集合
const ActivityList = ref([])
//创建分页对象
let pageInfo = ref({})
//定义路由对象
const router= useRouter()
//用户名字集合
const ownerList = ref([])

//表单数据对象
const searchCondition = ref({})
//表单提交对象
const searchConditionRef = ref()
// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
//加载市场活动列表
const loadData = (current,size) =>{
  console.log('负责人ID', searchCondition.value.ownerId)
  console.log('负责名称', searchCondition.value.name)
  console.log('活动预算',searchCondition.value.cost)
  console.log('创建时间', searchCondition.value.createTime)

  console.log('活动时间', searchCondition.value.activityTime)
  // 活动开始时间
  let startTime = ''
  // 活动结束时间
  let endTime = ''
  for (let key in searchCondition.value.activityTime) {
    if (key === '0') {
      startTime = searchCondition.value.activityTime[key]
    }
    if (key === '1') {
      endTime = searchCondition.value.activityTime[key]
    }
  }
  console.log('活动开始时间', startTime)
  console.log('活动结束时间', endTime)
  //分页参数
  let params  =  {
    current: current,
    size: size,
    name: searchCondition.value.name,
    ownerId: searchCondition.value.ownerId,
    cost: searchCondition.value.cost,
    createTime: searchCondition.value.createTime,
    startTime: startTime,
    endTime: endTime
  }
  console.log('分页参数', params)
  doGet('/api/activity/page',params).then(resp => {
    if (resp.data.code === 200){
      ActivityList.value = resp.data.data.list
      pageInfo.value = resp.data.data.total
    }else {
      showMessage("数据加载失败，请稍后重试"+resp.data.msg,"error")
    }
  })
}
//加载用户列表 --取出名字
const loadOwners = () =>{
  doGet('/api/user/list').then(resp => {
    if (resp.data.code === 200){
      ownerList.value = resp.data.data
    }else {
      showMessage("数据加载失败，请稍后重试"+resp.data.msg,"error")
    }
  })
}
//删除活动
const toDeleteAct = (id) =>{
  confirmMessage("确定删除该活动吗？").then(()=>{
    doDelete('/api/activity/'+id,{}).then((resp)=>{
      if (resp.data.code === 200){
        showMessage("删除成功","success")
        loadData(1,10)

      }else
        showMessage("删除失败"+resp.data.msg,"error")
    })
  })

}
let ActArr = []
//获取选中行
const selectionChange = (newSelection) =>{
  ActArr = []
  newSelection.forEach((item)=>{
    ActArr.push(item.id)
  })
  console.log(ActArr)
}
//批量删除
const BatchDeleteAct = ()=>{
  //判断是否选中了数据
  if (ActArr.length === 0){
    showMessage("请选择要删除的数据","warning")
    return
  }
  confirmMessage("确定要删除吗？").then(()=>{
    doDelete('/api/activity/batch/'+ActArr).then((resp)=>{
      if (resp.data.code === 200){
        showMessage("删除成功","success")
        loadData(1,10)

      }else
        showMessage("删除失败"+resp.data.msg,"error")
    })
  })


}

//详情页面
const activityDetails = (id) =>{
  router.push('/index/activity/details/'+id)
}
//编辑页面
const activityEdit=(id)=>{
  router.push('/index/activity/edit/'+id)
}
// 页面加载完成后执行
onMounted(()=>{
  // 加载用户列表
  loadData(1,10)
  loadOwners()
})
</script>

<template>
  <el-form
      ref="searchConditionRef"
      :inline="true"
      :model="searchCondition"
      class="demo-form-inline">

    <el-form-item label="负责人" prop="ownerId">

      <el-select
          v-model="searchCondition.ownerId"
          placeholder="请选择负责人"
          style="width: 240px">
        <el-option
            v-for="user in ownerList"
            :key="user.id"
            :label="user.name"
            :value="user.id"
        />
      </el-select>
    </el-form-item>


    <el-form-item label="活动名称" prop="name">
      <el-input v-model="searchCondition.name" placeholder="请输入活动名称"/>
    </el-form-item>

    <el-form-item label="活动时间" prop="activityTime">
      <el-date-picker
          v-model="searchCondition.activityTime"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>

    <el-form-item label="活动预算" prop="cost">
      <el-input v-model="searchCondition.cost"  placeholder="请输入活动预算"/>
    </el-form-item>

    <el-form-item label="创建时间" prop="createTime">
      <el-date-picker
          v-model="searchCondition.createTime"
          type="datetime"
          placeholder="请选择创建时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>

    <el-form-item label=" ">
      <el-button type="primary" @click="loadData(1,10)">搜索</el-button>
      <el-button @click="resetForm(searchConditionRef)">重置</el-button>
    </el-form-item>

  </el-form>


  <hr>
  <div> </div>
<!-- 按钮 -->
  <el-button type="primary" round @click="router.push('/index/activity/add')">录入市场活动</el-button>
  <el-button type="danger" round @click="BatchDeleteAct" v-if="loginUser.id===1">批量删除</el-button>
  <br>
  <!--表格-->
  <div class="table-ss">
    <el-table
        :data="ActivityList"
        row-key="id"
        style="width: 100%"
        @selection-change="selectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />

      <el-table-column type="index"  label="序号" width="55" />
      <el-table-column property="ownerName" label="负责人" width="120" />
      <el-table-column property="name" label="活动名称" width="120" />
      <el-table-column property="startTime" label="开始时间" width="200" />
      <el-table-column property="endTime" label="结束时间" width="200" />
      <el-table-column property="cost" label="活动预算" width="120" />
      <el-table-column property="createTime" label="创建时间" width="200" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="activityDetails(scope.row.id)">
            详情
          </el-button>
          <el-button type="success" size="small" @click="activityEdit(scope.row.id)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="toDeleteAct(scope.row.id)" v-if="loginUser.id===1">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <br>
  <!-- 分页 -->
  <div class="fy-ss">
    <el-pagination background layout="prev, pager, next" :total=pageInfo @change="loadData"/>
  </div>
</template>

<style scoped>
.fy-ss{
  margin-top: 10px;
  margin-left: 500px;;
}
</style>